package Algorithm.dynamic.palindrome;

public class FindPalindromeByPoint extends Palindrome {

    int length = 1;
    String answerStr = "";

    public String FindPalindrome(String source) {
        FindPalindromeByPoint so = new FindPalindromeByPoint();
        if (source == null || source.length() == 0) {
            return "";
        }
        so.answerStr = so.longestPalindrome(source);
        if (so.longestPalindrome(source).equals("")) {
            so.answerStr = String.valueOf(source.charAt(0));
        }
        return so.answerStr;
    }


    public String longestPalindrome(String s) {
        for (int i = 0; i < s.length() - 2; i++) {
            int temp = solution(s, i, i);
            int temp2 = solution(s, i, i + 1);
            if (temp > length && temp != -1) {
                answerStr = s.substring(i - temp + 1, i + temp);
                length = temp;
            }
            if (temp2 >= length && temp != -1) {
                answerStr = s.substring(i - temp2 + 1, i + 1 + temp2);
                length = temp2;
            }
        }
        return answerStr;
    }

    public int solution(String sourceStr, int position, int position2) {
        int left = position;
        int right = position2;
        boolean flag = false;
        while (left >= 0 && right <= sourceStr.length() - 1) {
            if (sourceStr.charAt(left) != sourceStr.charAt(right)) {
                return flag ? right - position2 : -1;
            }
            flag = true;
            left--;
            right++;
        }
        return flag ? right - position2 : -1;
    }
}